package xuli.dao.impl;

import entity.Product_Comment;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import util.C3P0Util;
import util.PageUtil;
import xuli.dao.ProductCommentDao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @author xuli
 */
public class ProductCommentDaoImpl implements ProductCommentDao {

    private QueryRunner queryRunner = new QueryRunner(C3P0Util.getDataSource());

    @Override
    public List<Product_Comment> findByPages(PageUtil<Product_Comment> pageUtil, String productId) {
        String sql = "select * from product_comment where product_id=? and audit_status=1 limit ?,?";
        List<Product_Comment> productComments = null;

        try {
            productComments = queryRunner.query(sql, new BeanListHandler<>(Product_Comment.class), productId, pageUtil.getPageSize() * (pageUtil.getPageNo() - 1), pageUtil.getPageSize());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return productComments;
    }

    @Override
    public Integer getTotalCount(String productId) {
        String sql = "select count(*) from product_comment where product_id=? and audit_status=1";
        Integer count = null;
        try {
            count = queryRunner.query(sql, rs -> {
                if (rs.next()) {
                    return rs.getInt(1);
                } else {
                    return null;
                }
            }, productId);

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return count;
    }
}
